/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ClientTool.java
 *
 * Created on 2011-12-22, 13:18:25
 */
package patrolclient;

import com.surelution.core.drivers.CommunicationException;
import com.surelution.core.drivers.Connection;
import com.surelution.core.drivers.DriverFactory;
import com.surelution.core.drivers.Wand;
import com.surelution.core.drivers.kh.KhLibrary;
import java.awt.Color;
import java.awt.Cursor;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Node;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

/**
 *
 * @author johnny
 */
public class ClientTool extends javax.swing.JDialog {

    private Config config;
    /** Creates new form ClientTool */
    public ClientTool(java.awt.Frame parent) {
        super(parent);
        initComponents();
        getRootPane().setDefaultButton(btReadInfo);
        config = new Config();
        txtProtocol.setText(config.get(Config.PROTOCOL));
        txtHost.setText(config.get(Config.HOST));
        txtPort.setText(config.get(Config.PORT));
        txtApp.setText(config.get(Config.APP));
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        btReadInfo = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLWandSnInfo = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        txtProtocol = new javax.swing.JTextField();
        txtHost = new javax.swing.JTextField();
        txtPort = new javax.swing.JTextField();
        txtApp = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        lblTimeError = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setModalityType(null);
        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(patrolclient.PatrolClientApp.class).getContext().getResourceMap(ClientTool.class);
        jLabel1.setFont(resourceMap.getFont("jLabel1.font")); // NOI18N
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        btReadInfo.setText(resourceMap.getString("btReadInfo.text")); // NOI18N
        btReadInfo.setName("btReadInfo"); // NOI18N
        btReadInfo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btReadInfoActionPerformed(evt);
            }
        });

        jLabel2.setFont(resourceMap.getFont("jLabel2.font")); // NOI18N
        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        jLWandSnInfo.setText(resourceMap.getString("jLWandSnInfo.text")); // NOI18N
        jLWandSnInfo.setName("jLWandSnInfo"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        jLabel6.setText(resourceMap.getString("jLabel6.text")); // NOI18N
        jLabel6.setName("jLabel6"); // NOI18N

        txtProtocol.setText(resourceMap.getString("txtProtocol.text")); // NOI18N
        txtProtocol.setName("txtProtocol"); // NOI18N

        txtHost.setText(resourceMap.getString("txtHost.text")); // NOI18N
        txtHost.setName("txtHost"); // NOI18N

        txtPort.setText(resourceMap.getString("txtPort.text")); // NOI18N
        txtPort.setName("txtPort"); // NOI18N

        txtApp.setText(resourceMap.getString("txtApp.text")); // NOI18N
        txtApp.setName("txtApp"); // NOI18N

        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        lblTimeError.setText(resourceMap.getString("lblTimeError.text")); // NOI18N
        lblTimeError.setName("lblTimeError"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(214, Short.MAX_VALUE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(168, 168, 168))
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel6)
                        .addGap(18, 18, 18)
                        .addComponent(txtApp, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(18, 18, 18)
                                .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addGap(18, 18, 18)
                                .addComponent(txtHost, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(18, 18, 18)
                        .addComponent(jButton1))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(18, 18, 18)
                        .addComponent(txtProtocol, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(169, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(74, 74, 74)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblTimeError, javax.swing.GroupLayout.PREFERRED_SIZE, 374, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(75, 75, 75)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(btReadInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))))
                .addContainerGap(50, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(126, 126, 126)
                .addComponent(jLWandSnInfo, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)
                .addGap(141, 141, 141))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(jLabel1)
                .addGap(36, 36, 36)
                .addComponent(btReadInfo)
                .addGap(10, 10, 10)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLWandSnInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblTimeError, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(txtProtocol, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(txtHost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(txtApp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(56, 56, 56)
                        .addComponent(jButton1)))
                .addContainerGap(39, Short.MAX_VALUE))
        );

        btReadInfo.getAccessibleContext().setAccessibleName(resourceMap.getString("jButton1.AccessibleContext.accessibleName")); // NOI18N

        pack();
    }// </editor-fold>//GEN-END:initComponents
        private Wand wand;

        
private void btReadInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btReadInfoActionPerformed
        PatrolClientApp.getApplication().getMainFrame().setCursor(Cursor.WAIT_CURSOR);
        Properties prop = new Properties();
        prop.put("type", KhLibrary.MT_USB);
//        prop.put("port", "com3"); 
        prop.put("baut", 460800);

        Connection conn;
        System.out.println("connectDevice...");
        try {
            conn = DriverFactory.buildConnection("com.surelution.core.drivers.kh_v2.KhConnection", prop );
            System.out.println("conn:"+conn);
            this.jLWandSnInfo.setForeground(Color.black);
            this.jLWandSnInfo.setText("正在连接设备...");
            wand = conn.prepareWand();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(PatrolClientView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(PatrolClientView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(PatrolClientView.class.getName()).log(Level.SEVERE, null, ex);
        }
        String wandSn = wand.getId();
        System.out.println("Connecting success,Now start to verify device...");
        System.out.println(wandSn);
        try {
            wand.loadDefaultConfigure();
        } catch (CommunicationException ex) {
            Logger.getLogger(ClientTool.class.getName()).log(Level.SEVERE, null, ex);
        }

        //verify
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            Config c = new Config();
            StringBuilder query = new StringBuilder(c.getFullApplicationUrl());
            query.append("/clientGate/shakeHands?wandSn=");
            query.append(wandSn);
            query.append("&terminalTime=");
            query.append(sdf.format(wand.getTime()));
            query.append("&stationTime=");
            query.append(sdf.format(new Date()));
            System.out.println(query.toString());
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(query.toString());
            try {
                HttpResponse response = client.execute(get);
                InputStream is = response.getEntity().getContent();
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder;
                builder = factory.newDocumentBuilder();
                Document doc;
                doc = builder.parse(is);
                doc.getDocumentElement().normalize();
                NodeList nodeList = doc.getElementsByTagName("code");
                if(nodeList != null) {
                    Node codeNode = nodeList.item(0);
                    String code = codeNode.getTextContent();
                    System.out.println("start to verify!");
                    if("FOUND-WAND".contains(code)) {
                        String user = doc.getElementsByTagName("user").item(0).getTextContent();
                        System.out.println("巡更棒序号：" + wandSn + " 使用者：" + user);
                        this.jLWandSnInfo.setText("巡更棒序号：" + wandSn + " 使用者：" + user);       
                        this.jLWandSnInfo.setForeground(Color.black);       
                    }
                    else {
                        System.out.println("读取设备信息失败，请重试!");
                        this.jLWandSnInfo.setForeground(Color.red);       
                        this.jLWandSnInfo.setText("读取设备失败,请重试！");       
                    }
                }
                
                
                NodeList nodeListTime = doc.getElementsByTagName("serverTime");
                if(nodeListTime != null) {
                    Node timeNode = nodeListTime.item(0);
                    String timeString = timeNode.getTextContent();
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        Date serverTime = format.parse(timeString);
                        long diff = serverTime.getTime() - System.currentTimeMillis();
                        long fiveMinute = 5 * 60 * 1000;
                        lblTimeError.setText("");
                        if(fiveMinute < Math.abs(diff)) {
                            lblTimeError.setForeground(Color.red);
                            lblTimeError.setText("你电脑的时间似乎有误，请准确对时，或联系管理员！");
                        } else {
                            wand.setTime(new Date());
                        }
                    } catch (ParseException ex) {
                        Logger.getLogger(ClientTool.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

            } catch (SAXException ex) {
                Logger.getLogger(PatrolClientView.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ParserConfigurationException ex) {
                Logger.getLogger(PatrolClientView.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(PatrolClientView.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        } catch (CommunicationException ex) {
            Logger.getLogger(PatrolClientView.class.getName()).log(Level.SEVERE, null, ex);
        }        
        // TODO add your handling code here:
            PatrolClientApp.getApplication().getMainFrame().setCursor(Cursor.DEFAULT_CURSOR);

}//GEN-LAST:event_btReadInfoActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        config.set(Config.PROTOCOL, txtProtocol.getText());
        config.set(Config.HOST, txtHost.getText());
        config.set(Config.PORT, txtPort.getText());
        config.set(Config.APP, txtApp.getText());
        config.saveConfig();
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ClientTool.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ClientTool.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ClientTool.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ClientTool.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                ClientTool dialog = new ClientTool(new javax.swing.JFrame());
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btReadInfo;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLWandSnInfo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel lblTimeError;
    private javax.swing.JTextField txtApp;
    private javax.swing.JTextField txtHost;
    private javax.swing.JTextField txtPort;
    private javax.swing.JTextField txtProtocol;
    // End of variables declaration//GEN-END:variables
}
